//
//  QLKPageControl.m
//

#import "QLKPageControl.h"

@interface QLKPageControl()
- (CGFloat)getPageViewWidth:(NSUInteger)pageNum;
- (CGFloat)getDotXWithIndex:(NSUInteger)index;
@end

@implementation QLKPageControl
@synthesize numberOfPages = _numberOfPages;
@synthesize currentPage = _currentPage;
- (CGFloat)getPageViewWidth:(NSUInteger)pageNum{
    return _numberOfPages * PAGE_VIEW_NORMAL_DOT_WIDTH + (pageNum - 1) * PAGE_VIEW_SPACE_BETWEEN_DOTS;
}
- (CGFloat)getDotXWithIndex:(NSUInteger)index{
    return index * (PAGE_VIEW_SPACE_BETWEEN_DOTS + PAGE_VIEW_NORMAL_DOT_WIDTH);
}

- (id)initWithPageNum:(NSUInteger)pageNum{
    self = [super initWithFrame:CGRectMake(0, 0, [self getPageViewWidth:pageNum], PAGE_VIEW_NORMAL_DOT_HEIGHT)];
    if (self) {
        _currentPage = 0;
        _numberOfPages = pageNum;
    }
    return self;
}

- (void)setNumberOfPages:(NSUInteger)pageNum {
    _numberOfPages = pageNum;
    
    if (_selectedDotView != nil) {
        return;
    }
    
    self.frame = CGRectMake(0, 0, [self getPageViewWidth:pageNum], PAGE_VIEW_NORMAL_DOT_HEIGHT);
    
    for (int i = 0; i < _numberOfPages; i++) {
        UIImageView *dotView = [[UIImageView alloc] initWithFrame:CGRectMake([self getDotXWithIndex:i], 0, PAGE_VIEW_NORMAL_DOT_WIDTH, PAGE_VIEW_NORMAL_DOT_HEIGHT)];
        dotView.image = PAGE_VIEW_DOT_IMAGE;
        dotView.tag = 100+i;
        [self addSubview:dotView];
    }
    
    _selectedDotView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, PAGE_VIEW_HIGHLIGHT_DOT_WIDTH, PAGE_VIEW_HIGHLIGHT_DOT_WIDTH)];
    _selectedDotView.image = PAGE_VIEW_SELECTED_DOT_IMAGE;
    [self addSubview:_selectedDotView];
}

- (void)setInitStateFromNib:(NSUInteger)pageNum
{
    _currentPage = 0;
    _numberOfPages = pageNum;
    
    self.frame = CGRectMake(0, 0, [self getPageViewWidth:pageNum], PAGE_VIEW_NORMAL_DOT_HEIGHT);
    
    for (int i = 0; i < _numberOfPages; i++) {
        UIImageView *dotView = [[UIImageView alloc] initWithFrame:CGRectMake([self getDotXWithIndex:i], 0, PAGE_VIEW_NORMAL_DOT_WIDTH, PAGE_VIEW_NORMAL_DOT_HEIGHT)];
        dotView.image = PAGE_VIEW_DOT_IMAGE;
        dotView.tag = 100+i;
        [self addSubview:dotView];
    }
    
    _selectedDotView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, PAGE_VIEW_NORMAL_DOT_WIDTH, PAGE_VIEW_NORMAL_DOT_HEIGHT)];
    _selectedDotView.image = PAGE_VIEW_SELECTED_DOT_IMAGE;
    [self addSubview:_selectedDotView];
}

- (void)setCurrentPage:(NSUInteger)currentPage{
    _currentPage = currentPage;
    _selectedDotView.center = [self viewWithTag:100+currentPage].center;
}
- (void)dealloc{
}

@end
